@echo off
chcp 65001
setlocal EnableDelayedExpansion

:: Read version number
set /p VERSION=<version

:: Set directory and file names
set "RELEASES_DIR=releases"
set "PLATFORM_DIR=windows"
set "APP_NAME=UselessCapsLock"
set "RELEASE_NAME=%APP_NAME%-%VERSION%"
set "OUTPUT_DIR=%RELEASES_DIR%\%PLATFORM_DIR%\%RELEASE_NAME%"

:: Create release directory structure
if not exist "%RELEASES_DIR%" mkdir "%RELEASES_DIR%"
if not exist "%RELEASES_DIR%\%PLATFORM_DIR%" mkdir "%RELEASES_DIR%\%PLATFORM_DIR%"

:: Clean up old files
if exist "%OUTPUT_DIR%" rmdir /s /q "%OUTPUT_DIR%"
if exist "%OUTPUT_DIR%.zip" del /f /q "%OUTPUT_DIR%.zip"

:: Create output directory
mkdir "%OUTPUT_DIR%"

:: Get git commit hash
for /f "tokens=*" %%a in ('git rev-parse --short HEAD') do set COMMIT=%%a

:: Get build time
for /f "tokens=*" %%a in ('powershell -Command "Get-Date -Format 'yyyy-MM-dd HH:mm:ss'"') do set BUILD_DATE=%%a

:: Compile program
echo Compiling program...
go build -o "%OUTPUT_DIR%\%APP_NAME%.exe" -ldflags="-H windowsgui -s -w -X main.version=%VERSION% -X main.commit=%COMMIT% -X 'main.buildDate=%BUILD_DATE%'" -trimpath
if errorlevel 1 (
    echo Compilation failed!
    exit /b 1
)

:: Copy necessary files
echo Copying files...
if exist "config.json" copy /Y "config.json" "%OUTPUT_DIR%\" >nul
if exist "icon.ico" copy /Y "icon.ico" "%OUTPUT_DIR%\" >nul
if exist "README.md" copy /Y "README.md" "%OUTPUT_DIR%\" >nul
if exist "LICENSE" copy /Y "LICENSE" "%OUTPUT_DIR%\" >nul
if exist "web\static" xcopy /E /I /Y "web\static" "%OUTPUT_DIR%\web\static" >nul

:: Create default config file
if not exist "%OUTPUT_DIR%\config.json" (
    echo {> "%OUTPUT_DIR%\config.json"
    echo   "mappings": [>> "%OUTPUT_DIR%\config.json"
    echo     {>> "%OUTPUT_DIR%\config.json"
    echo       "source_key": "CapsLock",>> "%OUTPUT_DIR%\config.json"
    echo       "destination_key": "Esc">> "%OUTPUT_DIR%\config.json"
    echo     }>> "%OUTPUT_DIR%\config.json"
    echo   ],>> "%OUTPUT_DIR%\config.json"
    echo   "settings": {>> "%OUTPUT_DIR%\config.json"
    echo     "auto_open_config": false>> "%OUTPUT_DIR%\config.json"
    echo   }>> "%OUTPUT_DIR%\config.json"
    echo }>> "%OUTPUT_DIR%\config.json"
)

:: Create zip archive
echo Creating zip archive...
powershell -NoProfile -Command "Compress-Archive -Force -Path '%OUTPUT_DIR%' -DestinationPath '%OUTPUT_DIR%.zip'"

echo Packaging completed!
echo Output directory: %OUTPUT_DIR%
echo Zip archive: %OUTPUT_DIR%.zip

endlocal

pause